package com.starbaba.loantopic.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.google.gson.JsonObject;
import com.jumai.server.qiniu.QiniuUploadUtils;
import com.opensymphony.xwork2.ModelDriven;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.starbaba.common.ResultJson;
import com.starbaba.controllog.aop.LogAble;
import com.starbaba.controllog.model.ControlLogCategory;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.loantopic.model.LoanTopicModel;
import com.starbaba.loantopic.model.LoanTopicProductModel;
import com.starbaba.loantopic.model.LoanTopicTypeInfo;
import com.starbaba.loantopic.service.LoanTopicService;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.redis.JedisUtils;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;

@SuppressWarnings({"serial","unchecked","rawtypes","unused"})
public class LoanTopicAction extends BaseAction implements ModelDriven<LoanTopicModel> {

	@SuppressWarnings("deprecation")
    final BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	private LoanTopicModel model;

	private LoanTopicService service;

	private ArrayList<ControlLogCategory> logCategorysArrayList;

	@Autowired
	@Qualifier("loanTopicServiceImpl")
	public void setService(LoanTopicService service) {
		this.service = service;
	}

	@Override
	public LoanTopicModel getModel() {
		if (model == null) {
			model = new LoanTopicModel();
		}
		return model;
	}
    
	public String show(){
		return SUCCESS;
	}
	
	/**
	 * 专题列表
	 */
	public void getLoanTopicList() {
		
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		
		List list = service.getDataList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	/**
	 * 查询专题类型
	 * @return
	 * @throws Exception
	 */
	public void getTopicType() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		
		List<LoanTopicTypeInfo> list = dao.list("select id, name from loan_topic_type_info", LoanTopicTypeInfo.class);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	/**
	 * 查询专题信息
	 * @return
	 * @throws Exception
	 */
	public String getTopicInfo() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		String id = (String) paramsMap.get("id");
		if (!StringUtils.isEmpty(id)) {
			try {
				// 查询专题
				model = dao.get("select id,name,type,image1,image2,thumbnail,topic_desc,background_color from loan_topic_info where id = ?", LoanTopicModel.class, id);
				paramsMap.put("model", model);
			} catch (AppException e) {
				e.printStackTrace();
			}
		}
		return SUCCESS;
	}
	
	/**
	 * 查询专题产品
	 * 
	 * @return
	 * @throws Exception
	 */
	public void getTopicProductInfo() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		String id = (String) paramsMap.get("id");
		if (!StringUtils.isEmpty(id)) {
			// 查询专题产品
			List<LoanTopicProductModel> productList = dao.list("select ad_image, activity_url, product_id, product_desc, tag, position, online_time, offline_time, "
					+ " every_day_online_time, every_day_offline_time from loan_topic_product where status =1 and topic_id = ?",
					LoanTopicProductModel.class, id);
			pageResponse.setAaData(productList);
			pageResponse.setSEcho(pageRequest.getSEcho());
		}
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新增/编辑专题内容
	 * @throws ParseException
	 * @throws IOException
	 */
	public void saveLoanTopic() throws ParseException, IOException {

		boolean isValidate = true;
		ResultJson resultJs = new ResultJson();
		JsonObject result = new JsonObject();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String topicId = (String) paramsMap.get("id");
		String topicName = (String) paramsMap.get("name");
		String topicDesc = (String) paramsMap.get("topic_desc");

		if (isValidate) {
			if (StringUtils.isEmpty(topicId)) { // 新增
				model.setStatus(1);
				service.save(paramsMap, model);
				resultJs.msg = "保存成功";
			} else {// 更新
				try {
					service.update(paramsMap, model, Long.parseLong(topicId));
					JedisUtils.delKeys(LoanRedisKey.getTopicRelatedRedisKeys(Long.parseLong(topicId)));
					
					resultJs.msg = "更新成功";
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		try {
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    /**
     * 专题上线/下线
     * @throws NumberFormatException
     * @throws AppException
     */
	public void updateStatus() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String status = (String) paramsMap.get("status");
		try {
			String sql = "update loan_topic_info c set c.status = ? where c.id= ? ";
			dao.update(sql, status, Long.parseLong(id));
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "操作成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}
	
	/**
     * 删除专题
     * @throws NumberFormatException
     * @throws AppException
     */
	public void delTopic() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(
				Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		try {
			String sql = "update loan_topic_info set status = 2 where id= ? ";
			int delRow = dao.delete(sql, Long.parseLong(id)); // 状态改为不可用
			if (delRow == 1){ //  专题对应的产品改为不可用
				dao.delete("update loan_topic_product set status = 0 where topic_id = ?", Long.parseLong(id));
			}
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "操作成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void sortTab() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String prdidListStr = (String) paramsMap.get("prdSortList");
		String[] prdidList = prdidListStr.split("#");
		parsePageRequest();
		try {
			String sql = "update loan_product_info c set c.position = ? where c.id = ?";
			for (int index = 0; index < prdidList.length; ++index) {
				Long id = Long.parseLong(prdidList[index]);
				dao.update(sql, index, id);
			}
			responseSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			responseError(e);
		}
	}
    
	/**
	 * 排序
	 */
	public void sortPosition() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String valueindex = (String) paramsMap.get("valueindex");
		String ids = (String) paramsMap.get("ids");
		String[] idvalue = ids.split(",");
		String[] indexs = valueindex.split(",");
		parsePageRequest();
		try {
			String sql = "update loan_product_info c set c.position = ? where c.id = ?";
			for (int i = 0; i < indexs.length; i++) {
				Long id = Long.parseLong(idvalue[i]);
				int index = Integer.parseInt(indexs[i]);
				dao.update(sql, index, id);
			}
			responseSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			responseError(e);
		}
	}

	private void responseSuccess() {
		JsonObject result = new JsonObject();
		result.add("result", new ResultJson().toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 *
	 * @Title responseSuccess
	 * @Description <p>
	 *              返回错误信息
	 *              </p>
	 *              　　　　　
	 * @author zhengjunjie
	 * @dateTime 2015年10月16日 下午2:26:53
	 *
	 */
	private void responseError(Exception error) {
		StringWriter writer = new StringWriter();
		error.printStackTrace(new PrintWriter(writer, true));
		ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
		JsonObject result = new JsonObject();
		result.add("result", resultJson.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	private void loadLogCategory(String id, String name) {
		logCategorysArrayList.clear();
		ControlLogCategory logCategory = new ControlLogCategory();
		logCategory.setId(id);
		logCategory.setName(name);
		logCategorysArrayList.add(logCategory);
	}

	@Override
	public ArrayList<ControlLogCategory> getProduct() {
		return logCategorysArrayList;
	}

	public void delRedis() {
//		if (JedisUtils.exists("loan:activity_list")) {
//			JedisUtils.del("loan:activity_list");
//		}
		responseSuccess();
	}

	/*public void updatePosition() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String position = (String) paramsMap.get("position");
		String sql = "update loan_product_info set position= ? where id = ?";
		dao.update(sql, new Object[]{position,id});
		responseSuccess();
	}*/
	
	
	/**
	 * 修改位置
	 */
	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void updatePosition() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String position = (String) paramsMap.get("position");
		
		String sql = "update loan_product_info set position = ? where id = ?";
		
		try {
			if (position != null && position != "") {
				dao.update(sql, new Object[]{Integer.parseInt(position),id});
			} else {
				dao.update(sql, new Object[]{Integer.parseInt(position),id});
			}

			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "修改成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void showInvest() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String str = (String) paramsMap.get("ids");
		String status = (String) paramsMap.get("status");
		String[] ids = str.split(",");
		String sql = "update loan_product_info set status = ? where id =?";
		for (String id : ids) {
			if (!StringUtils.isEmpty(id)) {
				try {
					dao.update(sql, new Object[] { status, id });
				} catch (AppException e) {
					e.printStackTrace();
				}
			}
		}
		responseSuccess();
	}
	
	/**
	 * 时间比较
	 * @param date1
	 * @param date2
	 * @return
	 * @throws ParseException
	 */
	public static int compareDate(String date1,String date2) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(format.parse(date1));
		Date d1 = calendar.getTime();
		calendar.setTime(format.parse(date2));
		Date d2 = calendar.getTime();
		return d1.compareTo(d2); // d1 < d2  返回 -1 , d1 > d2 返回 1 , d1 = d2 返回 0
	}

	public String uploadToQiniu(File srcFile) {
		String iconUrl = null;
		if (srcFile.isDirectory()) {
			return iconUrl;
		} else {
			try {
				FileInputStream in = new FileInputStream(srcFile);
				// Zone为七牛机房所在地，根据源所在机房配置
		        Configuration config = new Configuration(Zone.zone0()); 
				iconUrl = QiniuUploadUtils.updateImg("loan", in, null, config);
		        in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return iconUrl;
	}
}
